package api

import (
	"openapi.itspire.cn/common/throw"
	"openapi.itspire.cn/config"
	"openapi.itspire.cn/database"
	"openapi.itspire.cn/model"
	"openapi.itspire.cn/utils"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	var login model.Login
	var user model.User

	if err := c.ShouldBindJSON(&login); err != nil {
		throw.ParameterError(c, err.Error())
		return
	}

	timestamp := uint64(time.Now().Unix())

	res := database.Ins.Where("contact = ?", login.Contact).First(&user)
	if res.RecordNotFound() == true {
		res := database.Ins.Where("nickname = ?", login.Nickname).First(&user)
		if res.RecordNotFound() == false {
			throw.LogicException(c, "昵称已存在", -1)
			return
		}
		user.Nickname = login.Nickname
		user.ContactType = login.ContactType
		user.Avatar = login.Avatar
		user.Contact = login.Contact
		user.CreateTime = timestamp
		res2 := database.Ins.NewRecord(user)
		if res2 {
			if err := database.Ins.Create(&user).Error; err != nil {
				panic(err)
			}
		}
	} else {
		if user.Status == 2 || user.DeleteTime > 0 {
			throw.AuthException(c, "账号尚未激活")
			return
		}
	}

	encrypt := utils.AesEncrypt(strconv.FormatUint(user.Id,10), config.Conf.App.AESKey, "CBC")
	maps := make(map[string]interface{})
	userInfo := make(map[string]interface{})
	userInfo["nickname"] = user.Nickname
	userInfo["avatar"] = user.Avatar
	maps["token"] = encrypt
	maps["userInfo"] = userInfo

	utils.Success(c, maps)
}
